<template>
	<view>
    <view class="chat-container">
        <view class="payment-overlay" id="paymentOverlay" v-if="showBuy">
            <view class="payment-message">陈粒1对1 24小时在线指导 78元/月</view>
            <button class="payment-button" @click="rechargeMembership(1)">支付78元</button>
        </view>
		<view class="payment-overlay" id="paymentOverlay" v-if="showBuyPic">
		    <view class="payment-message">20元120张聊天截图分析</view>
		    <button class="payment-button" @click="rechargeMembership(0)">支付20元</button>
		</view>
        <view>
			<view class="chat-header">
				<u-upload
				  :fileList="fileList1"
				  @afterRead="afterRead"
				  name="1"
				  multiple
				  :maxCount="4"
				  height="0"
				  width="0"
				  :deletable="true"
				  uploadText="最多可上传4张聊天记录"
				  ref="upload1"
				>
			    <image src="https://bdw-sh-1259268558.cos.ap-shanghai.myqcloud.com/liaotian6.png"
			    mode="widthFix" style="width: 300px;height: 100px;"></image>
				</u-upload>
			</view>
        </view>
		<scroll-view scroll-y="true" class="message-list" ref="scrollView" id="commentContainer" :scroll-top="commentScrollTop">	
		<view class="chat-box" id="commentContent">
			<view v-for="(message, index) in messages" :key="index" class="chat-message" :class="message.class" >
			  <view v-if="message.content.startsWith('https')" class="chat-bubble" :class="message.class">
			     <u-image :src="message.content" alt="聊天图片" width="100%" height="300rpx" mode="widthFix" style="width: 100px; height: 100px;"></u-image> <!-- 这里设置了图片宽高样式，可按需调整 -->
			  </view>
			  <view v-else class="chat-bubble" :class="message.class">
				<zero-markdown-view :markdown="message.content" class="markdown-content"></zero-markdown-view>
			  </view>
			</view>
		</view>
		</scroll-view>
        <view class="chat-input">
            <input type="text" id="userInput" placeholder="" v-model="userInput" v-if="this.sending == false">
			<input type="text" id="userInput" placeholder="回复中, 请勿在发送" v-model="userInput" v-else="this.sending == false">
            <button @click="sendMessage()" id="sendButton" v-if="this.sending == false">发送</button>
			<button id="sendButtonDisable" v-else="this.sending == false" style="background-color: gray;">发送</button>
            <button class="record-button" id="recordButton" style="display: none;">Hold to Talk</button>
            <button class="toggle-button" id="toggleButton" style="display: none;">Switch to Text</button>
        </view>
    </view>
	</view>
</template>
<script>
	let isRecording = false;
	let mediaRecorder;
	let audioChunks = [];
	let messageCount = 0;
	let serverFinTim = localStorage.getItem('finish_time');
	// let markid = getQueryString('mark_id');
	// console.log(markid);

	// document.addEventListener('DOMContentLoaded', () => {
	// 	const timestamp = parseInt(new Date().getTime() / 1000);
	// 	let orderNo = getQueryString('order_no');
	// 	if ((serverFinTim == null || serverFinTim - timestamp < 0) && orderNo != null) {
	// 		console.log(123);
	// 		setTimeout(() => {
	// 			getOrderResult(orderNo);
	// 		}, 1000);
	// 	}
	// 	loadChatHistory();
	// 	console.log(serverFinTim - timestamp);
	// 	if (serverFinTim != null && serverFinTim - timestamp > 0) {
	// 		console.log('finish_time');
	// 		startCountdown(serverFinTim - timestamp);
	// 	}
	// });
import COS from 'cos-js-sdk-v5';
export default {
	data() {
	  return {
		showBuyPic: false,
	    fileList1: [],
	    availableTimes: 0, // 可用次数
	    membershipExpiry: "", // 会员到期时间
	    showOverlay: false, // 控制浮层显示
	    analysisResult: "", // 分析结果
	    loading: false, // 控制加载提示
		orderNo: "",
		show: true,
		countdown: 60,
		userInput: '',
		commentScrollTop: 0,
		showBuy: false,
		messages: [],
		sending: false,
		id: 0
	  };
	},
	onLoad(options) {
		this.id = options.id;
		this.initChat();
		this.getResponse();
	},
	methods: {
		initChat() {
			console.log("initchat");
			this.messages.push({"class":"bot", "content": "对方正在输入中..."})
			// this.sending = true;
			
			fetch('https://data.bingdou.site/server/oneyuan/index/initChat', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				},
				body: JSON.stringify({
					"open_id": localStorage.getItem('openid'),
					"chat_id": this.id
				})
			})
			.then(response => response.json())
			.then(result => {
				this.messages.pop();
				// this.sending = false;
				if (result.code == 100) {
					this.showBuy = true;
				} else if (result.code == 200) {
					this.showBuyPic = true;
				} else {
					this.messages.push({"class":"bot", "content":result.data});
					this.$nextTick(() => {
					    this.scrollToBottom()
					})
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});
		},
		getResponse() {
			setInterval(() => {
				// this.messages.push({"class":"bot", "content":"对方正在输入中..."});
				fetch('https://data.bingdou.site/server/oneyuan/index/regularChatResponse', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json;charset=UTF-8'
					},
					body: JSON.stringify({
						"open_id": localStorage.getItem('openid'),
						"chat_id": this.id
					})
				})
				.then(response => response.json())
				.then(result => {
					// this.messages.pop();
					// this.sending = false;
					if (result.code == 100) {
						this.showBuy = true;
					} else {
						for (const item in result.data) {
							this.messages.push({"class":"bot", "content":result.data[item]});
							this.$nextTick(() => {
								this.scrollToBottom()
							})
							this.sleep(1500);
						}
					}
				})
				.catch(error => {
					console.error('Error:', error);
				});
			}, 1500);
		},
		getOrderResult(orderNo) {
			fetch('https://data.bingdou.site/server/bingdouyanzhidypay/index/getOrderPayment', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json;charset=UTF-8'
				},
				body: JSON.stringify({
					"out_order_no": orderNo
				})
			})
			.then(response => response.json())
			.then(result => {
				console.log(result);
				if (result.code == 0) {
					localStorage.setItem('finish_time', result.create_time);
					window.location.reload();
				} else {
					console.error('No data field in response:', result);
				}
			})
			.catch(error => {
				console.error('Error:', error);
			});
		},
		//滚动到底部
		scrollToBottom() {
			let query = uni.createSelectorQuery().in(this)
			query.select('#commentContainer').boundingClientRect()
			query.select('#commentContent').boundingClientRect()
			console.log(query);
			query.exec((res) => {
			//如果子元素高度大于父元素高度(显示高度)
			console.log(res);
			if (res[1].height > res[0].height) {
			  //计算出二者差值就是需要滚动的距离
			   this.commentScrollTop = res[1].height - res[0].height
			   
			}
		  })
		},
		
		async afterRead(event) {
		  // this.sending = true;
			
		  let lists = [].concat(event.file);
		  let fileListLen = this[`fileList${event.name}`].length;
		  lists.map((item) => {
			this[`fileList${event.name}`].push({
			  ...item,
			  status: 'uploading',
			  message: '上传中',
			});
		  });
		  for (let i = 0; i < lists.length; i++) {
			const result = await this.uploadFilePromise(lists[i]);
			let item = this[`fileList${event.name}`][fileListLen];
			this[`fileList${event.name}`].splice(
			  fileListLen,
			  1,
			  Object.assign(item, {
				status: 'success',
				message: '',
				url: result,
			  })
			);
			fileListLen++;
		  }
		  this.$refs.upload1.clear;
		  this.messages.push({"class":"user", "content": "您发送了截图"})
		  this.messages.push({"class":"bot", "content": "正在查看聊天截图中...稍等"})
		  this.$nextTick(() => {
		  	this.scrollToBottom()
		  })
		  
		  this.sending = true;
		  //分析截图
		  const response = await fetch('https://data.bingdou.site/server/oneyuan/index/chatImageAnalysis', {
			method: 'POST',
			headers: {
			  'Content-Type': 'application/json'
			},
			body: JSON.stringify({
			  open_id: localStorage.getItem('openid'),
			  image: this.fileList1.map(file => file.url),
			  chat_id: this.id,
			})
		  });
		  const data = await response.json();
		  
		  this.messages.pop();
		  this.sending = false;
		  // this.messages.pop();
		  if (data.code == 100) {
			this.showBuy = true;
		  } else {
			  for (const item in data.data) {
				this.messages.push({"class":"bot", "content":data.data[item]});
				this.$nextTick(() => {
					this.scrollToBottom()
				})
				this.sleep(1500);
			  }
			// this.messages.push({"class":"bot", "content":data.data});
			// this.$nextTick(() => {
				// this.scrollToBottom()
			// })
		  }
		},
		async sleep(ms) {
			return new Promise((resolve) => {
				setTimeout(resolve, ms);
			});
		},
		uploadFilePromise(file) {
		  return new Promise((resolve, reject) => {
			const fileKey = `aaa/${file.name}`;
			const cos = new COS({
			  SecretId: 'AKIDhK6oW96L8mJbKvreiZCpXIw6h973lBKH',
			  SecretKey: 'rWzJROAlA5mNsBJH2auyxqYi2EAvYYMw',
			});
			this.urlToFile(file.url, file.name, file.type)
			  .then((file1) => {
				cos.putObject(
				  {
					Bucket: 'jianji-1259268558',
					Region: 'ap-shanghai',
					Key: fileKey,
					Body: file1,
					onProgress: function (progressData) {
					  console.log(JSON.stringify(progressData));
					},
				  },
				  (err, data) => {
					if (err) {
					  console.error('上传失败: ', err);
					  reject(err);
					} else {
					  console.log('上传成功: ', data.Location);
					  resolve("https://" + data.Location);
					  // this.messages.push({"class":"picture", "content": "https://" + data.Location})
					  // this.$nextTick(() => {
						  // this.scrollToBottom()
					  // })
					}
				  }
				);
			  })
			  .catch((error) => {
				console.error('转换文件失败: ', error);
				reject(error);
			  });
		  });
		},
		urlToFile(url, filename, mimeType) {
		  return new Promise((resolve, reject) => {
			const xhr = new XMLHttpRequest();
			xhr.open('GET', url, true);
			xhr.responseType = 'blob';
			xhr.onload = function () {
			  if (xhr.status === 200) {
				const blob = xhr.response;
				const file = new Blob([blob], { type: mimeType });
				resolve(new File([file], filename, { type: mimeType }));
			  } else {
				reject(new Error('Failed to fetch the file'));
			  }
			};
			xhr.onerror = function () {
			  reject(new Error('Network error'));
			};
			xhr.send();
		  });
		},

		// saveMessageToBackup(role, content) {
			// const chatHistoryBackup = JSON.parse(localStorage.getItem('chatHistoryBackup')) || [];
			// chatHistoryBackup.push({ role, content });
			// localStorage.setItem('chatHistoryBackup', JSON.stringify(chatHistoryBackup));
		// },

		getQueryString(name) {
			var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return unescape(r[2]);
			}
		},

		async sendMessage() {
			// if (this.sending == true) {
				// return;
			// }
			const message = this.userInput.trim();

			if (message === '') return;

			messageCount++;

			this.messages.push({"class":"user", "content":message});

			// this.saveMessageToBackup('user', message);
			// this.inputBuffer.push(message);
			this.userInput = '';
			this.$nextTick(() => {
				this.scrollToBottom()
			})
			
			this.fetchResponse(message);
		},

		async fetchResponse(message) {
			// let previousMessages = localStorage.getItem('chatHistory');

			try {
				const response = await fetch('https://data.bingdou.site/server/oneyuan/index/getBotReply', {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({ 
						"open_id": localStorage.getItem('openid'),
						"chat_id": this.id,
						"message": message
					})
				});

				const data = await response.json();
				if (data.code == 100) {
					this.messages.pop();
					this.showBuy = true;
				} else {
					this.messages.push({"class":"bot", "content":data.data});
					this.$nextTick(() => {
						this.scrollToBottom()
					})
				}
			} catch (error) {
				console.error('Error:', error);
				// typingIndicator.remove();
			}
		},

		async rechargeMembership(type) {
		  // 请求服务端获取微信支付参数
		  try {
			const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
			  method: 'POST',
			  headers: {
				'Content-Type': 'application/json'
			  },
			  body: JSON.stringify({
				open_id: localStorage.getItem('openid'),
				type: type
			  })
			});
			const data = await response.json();
			this.orderNo = data.data.order_no;
				  
			if (typeof WeixinJSBridge == "undefined") {
			  if (document.addEventListener) {
				 document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
			  } else if (document.attachEvent) {
			     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		      }
			} else {
			  this.onBridgeReady(data);
			}
		  } catch (error) {
			console.error('请求支付参数时出错:', error);
		  }
		},
	
		onBridgeReady(data) {
		  var that = this
		  WeixinJSBridge.invoke('getBrandWCPayRequest', {
			  "appId": data.data.appId,     //公众号ID，由商户传入     
			  "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
			  "nonceStr": data.data.nonceStr,      //随机串     
			  "package": data.data.package,
			  "signType": "MD5",     //微信签名方式：     
			  "paySign": data.data.paySign,
		  },
		  function(res) {
			  if (res.err_msg == "get_brand_wcpay_request:ok") {
				  // 使用以上方式判断前端返回,微信团队郑重提示：
				  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
				  that.pollPaymentResult();
			  }
		  });
		},
		cancel() {
		  this.show = false;
		},
		async pollPaymentResult() {
		  const pollInterval = 1000; // 轮询间隔时间（毫秒）
		  const maxAttempts = 20; // 最大轮询次数
		  let attempts = 0;
				const orderNo = this.orderNo;
		  const poll = async () => {
			try {
			  const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
			  const data = await response.json();
			  if (data.code === 0) {
				// 支付成功
				// alert('充值成功');
				this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
				return;
			  } else if (data.code === 1) {
				// 支付进行中，继续轮询
				if (attempts < maxAttempts) {
				  attempts++;
				  setTimeout(poll, pollInterval);
				} else {
				  alert('支付结果查询超时');
				}
			  } else {
				// 支付失败
				alert('支付失败');
			  }
			} catch (error) {
			  console.error('查询支付结果时出错:', error);
			  alert('查询支付结果时出错');
			}
		  };
		
		  poll();
		}
	},
}
</script>


<style>
	body {
		font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
		background-color: #f5f5f5;
		margin: 0;
		padding: 0;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
	}
	.message-list {
		flex-grow: 1; /* 占用所有可用空间 */
		overflow-y: auto; 
		margin-top: 15rpx;
	}
	.chat-container {
		margin-top: 3rpx;
		display: flex;
		  flex-direction: column;
		  height: 100%; 
	}
	.chat-header {
		background-color: #dcf8c6;
		color: white;
		/* padding: 10px 20px; */
		/* display: flex; */
		/* align-items: center; */
		display: flex;
		justify-content: center;
		/* margin-top: 10px; */
		/* margin-bottom: 1px; /* 添加底部间距 */
	}
	.chat-header img {
		border-radius: 50%;
		width: 80px;
		height: 60px;
		margin-right: 20px;
	}
	.chat-header .info-container {
		display: flex;
		flex-direction: column;
	}
	.chat-header .intro {
		font-size: 16px;
		margin: 5px 0;
	}
	.chat-header .intro:first-child {
		font-weight: bold;
	}
	.countdown-timer {
		font-size: 16px;
		font-weight: bold;
		color: white;
		margin-top: 5px;
	}
	.chat-box {
		flex: 1;
		overflow-y: auto;
		padding: 20px;
		display: flex;
		flex-direction: column;
	}
	.chat-message {
		margin: 10px 0;
		display: flex;
		flex-direction: column;
	}
	.chat-message.user {
		align-items: flex-end;
	}
	.chat-message.picture {
		align-items: flex-end;
		margin-bottom: 100rpx;
	}
	.chat-message.bot {
		align-items: flex-start;
	}
	.chat-bubble {
		max-width: 70%;
		padding: 5px 5px;
		border-radius: 20px;
		line-height: 1.5;
		margin-bottom: 5px;
	}
	.chat-bubble.user {
		background-color: limegreen;
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.picture {
		border-radius: 20px 20px 0 20px;
	}
	.chat-bubble.bot {
		background-color: #fff;
		border: 1px solid #ececec;
		border-radius: 20px 20px 20px 0;
	}
	.chat-input {
		display: flex;
		padding: 10px;
		border-top: 1px solid #ececec;
		background-color: #fafafa;
		align-items: center;
	}
	.chat-input input {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
	}
	.chat-input button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		flex-shrink: 0;
		height: 40px;
	}
	.chat-input button.voice {
		margin-left: 10px;
	}
	.chat-input button:hover {
		background-color: #005bb5;
	}
	.record-button {
		flex: 1;
		padding: 10px;
		border: 1px solid #ececec;
		border-radius: 20px;
		margin-right: 10px;
		font-size: 16px;
		background-color: white !important;
		color: black !important;
		cursor: pointer;
		text-align: center;
	}
	.toggle-button {
		padding: 0 20px;
		border: none;
		background-color: #007aff;
		color: white;
		border-radius: 20px;
		cursor: pointer;
		font-size: 16px;
		height: 40px;
	}
	.toggle-button:hover {
		background-color: #005bb5;
	}
	.small-button {
		padding: 5px 10px;
		font-size: 12px;
		margin-top: 5px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 10px;
		cursor: pointer;
	}
	.small-button:hover {
		background-color: #005bb5;
	}
	.converted-text {
		background-color: #f1f1f1;
		border: 1px solid #ececec;
		border-radius: 10px;
		padding: 10px;
		margin-top: 5px;
		font-style: italic;
		color: #333;
	}
	.payment-overlay {
		display: flex;
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
		flex-direction: column;
		z-index: 10;
	}
	.payment-message {
		/* background-color: #ffffff; */
		padding: 20px;
		border-radius: 10px;
		text-align: center;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		margin-bottom: 20px;
		font-size: 18px;
		width: 80%;
		color: #333;
	}
	.payment-button {
		padding: 5px 30px;
		background: linear-gradient(90deg, #ff7e5f, #feb47b);
		color: white;
		border: none;
		border-radius: 30px;
		cursor: pointer;
		font-size: 18px;
		font-weight: bold;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.payment-button:hover {
		background: linear-gradient(90deg, #ff6a4a, #fd9c6e);
		box-shadow: 0 6px 15px rgba(0, 0, 0, 0.3);
	}
	.fixed-buttons {
		position: fixed;
		bottom: 100px;
		right: 20px;
		display: flex;
		flex-direction: column;
		gap: 10px;
	}
	.role-button, .upload-button {
		padding: 10px 20px;
		background-color: #007aff;
		color: white;
		border: none;
		border-radius: 20px;
		cursor: pointer;
		font-size: 14px;
		box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
		transition: background 0.3s, box-shadow 0.3s;
	}
	.role-button:hover, .upload-button:hover {
		background-color: #005bb5;
	}
	.modal {
		display: none;
		position: fixed;
		z-index: 100;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		overflow: auto;
		background-color: rgba(0, 0, 0, 0.5);
		justify-content: center;
		align-items: center;
	}
	.modal-content {
		background-color: #fefefe;
		margin: 15% auto;
		padding: 20px;
		border: 1px solid #888;
		width: 80%;
		max-width: 400px;
		border-radius: 10px;
		text-align: center;
	}
	.close {
		color: #aaa;
		float: right;
		font-size: 28px;
		font-weight: bold;
	}
	.close:hover,
	.close:focus {
		color: black;
		text-decoration: none;
		cursor: pointer;
	}
	@media (max-width: 600px) {
		.chat-container {
			width: 100%;
			height: 100vh;
			border-radius: 0;
		}
		.chat-box {
			padding: 10px;
		}
		.chat-input input {
			font-size: 14px;
			padding: 8px;
		}
		.chat-input button {
			font-size: 14px;
			padding: 0 15px;
			height: 36px;
		}
		.record-button {
			padding: 8px;
			height: 36px;
		}
		.toggle-button {
			height: 36px;
		}
	}
</style>